/**
 * 〈所属模块〉
 * 〈功能描述〉
 *
 * @author Lcs
 * @date 2017/9/15 13:27
 */

import React, { Component } from "react";
import {
  StyleSheet, Text, View, TouchableOpacity, TextInput, DeviceEventEmitter,
} from "react-native";
import { connect } from "react-redux"; // 引入connect函数
import * as bindMobileAction from "../actions/bindMobileAction"; // 导入action方法
import {
  Color, ScreenWidth, FontSize, scale,
} from "../common";
import NavigatorUtil from "../utils/NavigatorUtil";
import BasePage from "../widget/common/BasePage";
import Button from "../widget/common/NCButton";
import { isEmpty } from "../utils/utils";

const VERIFYCODELENGTH = 6;

let mobile;
let type;
let interval;

class BindMobile extends Component {
  constructor(props) {
    super(props);
    mobile = NavigatorUtil.getPageParam(props, "mobile");
    type = NavigatorUtil.getPageParam(props, "type");
  }

  componentWillMount() {
    this.startCountDown();
  }

  componentWillUnmount() {
    const { props } = this;
    interval && clearInterval(interval);
    props.dispatch(bindMobileAction.bingMobileUnmount());
  }

  handleClick = () => {
    const { props } = this;
    const { bindMobileReducer } = props;
    const { code } = bindMobileReducer;
    props.dispatch(
      bindMobileAction.bindMobile(mobile, code, res => {
        DeviceEventEmitter.emit("BINDMOBILESUCCESS", mobile);
        setTimeout(() => NavigatorUtil.bindMobileBack(), 100);
      }),
    );
  };

  startCountDown = () => {
    const { props } = this;
    let num = 59;
    interval = setInterval(() => {
      props.dispatch(bindMobileAction.countDown(num));
      num -= 1;
      if (num < 0) {
        interval && clearInterval(interval);
      }
    }, 1000);
  };

  inputCode = text => {
    const { props } = this;
    props.dispatch(bindMobileAction.inputCode(text));
    if (this.input && this.input.isFocused() && text.length === VERIFYCODELENGTH) {
      this.input.blur();
    }
  };

  renderCodeItems() {
    const { props } = this;
    const { bindMobileReducer } = props;
    const { code } = bindMobileReducer;
    const codeItems = [];
    for (let i = 0; i < VERIFYCODELENGTH; i += 1) {
      codeItems.push(
        <View style={styles.codeItemContainer} key={String(i)}>
          <Text style={styles.codeItemText}>{code[i]}</Text>
        </View>,
      );
    }
    return codeItems;
  }

  render() {
    const { props } = this;
    const { bindMobileReducer } = props;
    const { code, loading, countDownNum } = bindMobileReducer;
    const isCounDown = !isEmpty(countDownNum);
    const isCodeDown = code.length === VERIFYCODELENGTH;
    return (
      <BasePage style={styles.container} showLoading={loading}>
        <Text style={styles.textMain}>绑定关联手机号</Text>
        <Text style={styles.textDesc}>{`已为您的手机${mobile.slice(7, 11)}发送验证码`}</Text>
        <TextInput
          ref={c => (this.input = c)}
          value={code}
          onChangeText={this.inputCode}
          maxLength={VERIFYCODELENGTH}
          autoFocus
          keyboardType="numeric"
          style={styles.input}
          underlineColorAndroid={Color.transparent}
          placeholder="请输入code"
          enablesReturnKeyAutomatically={false}
          placeholderTextColor={Color.text_assist}
        />
        <TouchableOpacity
          activeOpacity={1.0}
          onPress={() => this.input && !this.input.isFocused() && this.input.focus()}
        >
          <View style={styles.itemRowSpace}>{this.renderCodeItems()}</View>
        </TouchableOpacity>
        <TouchableOpacity
          activeOpacity={0.8}
          disabled={isCounDown}
          onPress={() => props.dispatch(bindMobileAction.getSmsCode(mobile, type, this.startCountDown))}
        >
          <Text style={[styles.textSubMain, { color: isCounDown ? Color.text_title : "#2682D6" }]}>
            {`重新发送${countDownNum}`}
          </Text>
        </TouchableOpacity>
        <Button
          disabled={!isCodeDown}
          onPress={this.handleClick}
          buttonStyle={isCodeDown ? styles.btnContainer : styles.btnDisContainer}
          textStyle={styles.btnText}
          title="下一步"
        />
      </BasePage>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Color.white,
    alignItems: "center",
    paddingTop: scale * 16,
  },
  codeItemContainer: {
    height: scale * 48,
    width: ScreenWidth / (2 * VERIFYCODELENGTH),
    alignItems: "center",
    justifyContent: "center",
    borderBottomWidth: 1,
    borderColor: Color.text_assist,
  },
  codeItemText: {
    fontSize: FontSize.SIZE_18,
    color: Color.text_title,
  },
  textMain: {
    fontSize: FontSize.SIZE_22,
    color: Color.text_title,
    marginTop: scale * 12,
    width: ScreenWidth - scale * 32,
  },
  textDesc: {
    fontSize: FontSize.SIZE_12,
    color: Color.text_desc,
    marginTop: scale * 8,
    marginBottom: scale * 12,
    width: ScreenWidth - scale * 32,
  },
  textSubMain: {
    fontSize: FontSize.SIZE_12,
    color: Color.text_title,
    marginTop: scale * 16,
    marginBottom: scale * 18,
  },
  itemRowSpace: {
    height: scale * 48,
    width: ScreenWidth - scale * 64,
    marginTop: scale * 16,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  btnContainer: {
    marginTop: scale * 48,
    height: 44 * scale,
    width: ScreenWidth - scale * 64,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: Color.tab_yellow,
    borderWidth: 0,
  },
  btnDisContainer: {
    marginTop: scale * 48,
    height: 44 * scale,
    width: ScreenWidth - scale * 64,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#DEB108",
    borderWidth: 0,
  },
  btnText: {
    fontSize: FontSize.SIZE_17,
    color: Color.white,
  },
  input: {
    width: 0,
    height: 0,
  },
});

const reducers = state => {
  return {
    bindMobileReducer: state.bindMobileReducer,
  };
};

export default connect(reducers)(BindMobile);
